<?php

namespace app\admin\controller;

use think\facade\Request;
use app\admin\model\Admin;
use think\facade\Session;
use app\admin\service\LoginService;
use app\common\Common;

class Login
{
    private $service;

    public function __construct(LoginService $service)
    {
        $this->service = $service;
    }

    // 渲染登录页面
    public function index()
    {
        return view();
    }

    /**
     * 后台用户登录
     * 
     * @dateTime 2022/09/06
     * @author zhixiang0215@126.com
     * @param string username
     * @param string password
     * @return json
     */
    public function login()
    {
        $params = Request::param();

        try {
            validate(\app\admin\validate\Login::class)->scene('login')->check($params);
        } catch (\Exception $e) {
            return Common::fail($e->getError());
        }

        $result = $this->service->userLogin($params);

        if ($result) {
            return Common::fail($result['message'], $result['code']);
        }
        return Common::success();
    }

    /**
     * 后台用户注册
     * 
     * @dateTime 2022/09/06
     * @author zhixiang0215@126.com
     * @param string username
     * @param string password
     * @return json
     */
    public function register()
    {
        $params = Request::param();

        try {
            validate(\app\admin\validate\Login::class)->scene('register')->check($params);
        } catch (\Exception $e) {
            return Common::fail($e->getError());
        }

        $result = $this->service->userRegister($params);

        if ($result) {
            return Common::fail($result['message'], $result['code']);
        }
        return Common::success();
    }

    // 渲染注册页面
    public function reg()
    {
        return view();
    }

    // 退出登录
    public function exitLogin()
    {
        Session::set('user_id', '');
        Session::set('user_name', '');
        Session::set('rule_id', '');
        Session::set('allauth', '');
        return redirect(url('admin/login/index'));
    }
}